import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { LZRequestInterceptors, LZRequestConfig } from './type'
import router from '@/router'
import localCache from '@/utils/cache'
import { ElLoading, ElMessage } from 'element-plus'

const DEAFULT_LOADING = true

class LZRequest {
  instance: AxiosInstance
  interceptors?: LZRequestInterceptors
  showLoading: boolean
  loading?: any

  constructor(config: LZRequestConfig) {
    // 创建axios实例
    this.instance = axios.create(config)

    // 保存基本信息
    this.showLoading = config.showLoading ?? DEAFULT_LOADING
    this.interceptors = config.interceptors

    // 使用拦截器
    // 1.从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    // 2.添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: 'Loading....',
            background: 'rgba(0, 0, 0, 0.5)'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        // 将loading移除
        this.loading?.close()
        // console.log(res)
        const data = res.data
        // console.log(data)
        if (data.code === 11) {
          console.log('请求失败~, 错误信息')
          console.log(data.data)
          ElMessage.error('Please relogin.')
          localCache.clearCache()
          router.push('/login')
        } else if (data.code === 1) {
          ElMessage.error(data.data)
        } else {
          return data
        }
      },
      (err) => {
        // 将loading移除
        this.loading?.close()

        // 例子: 判断不同的HttpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log('404的错误~')
        }
        return err
      }
    )
  }

  request<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 1.单个请求对请求config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      // 2.判断是否需要显示loading
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 1.单个请求对数据的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          // 2.将showLoading设置true, 这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING

          // 3.将结果resolve返回出去
          resolve(res)
        })
        .catch((err) => {
          // 将showLoading设置true, 这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING
          reject(err)
          return err
        })
    })
  }

  get<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }

  post<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }

  delete<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  patch<T = any>(config: LZRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }

  downloadFile(url: string, options = {}) {
    return new Promise((resolve, reject) => {
      // console.log(`${url} 请求数据，参数=>`, JSON.stringify(options))
      // axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
      axios({
        method: 'post',
        url: 'http://127.0.0.1:8000/api' + url, // 请求地址
        data: options, // 参数
        responseType: 'blob' // 表明返回服务器返回的数据类型
      }).then(
        (response) => {
          // console.log("下载响应",response)
          resolve(response.data)
          const blob = new Blob([response.data])
          // 切割出文件名
          const fileNameEncode = response.headers['Content-Disposition']
            ?.split(';')[1]
            .split('filename=')[1]
          // 解码
          console.log('文件下载，后端返回的内容：', response)
          console.log('文件切割出文件名：', fileNameEncode)

          // const fileName = decodeURIComponent(fileNameEncode)
          // // console.log("fileName",fileName)
          // const down = document.createElement('a')
          // down.download = fileName
          // down.style.display = 'none' //隐藏,没必要展示出来
          // down.href = URL.createObjectURL(blob)
          // document.body.appendChild(down)
          // down.click()
          // URL.revokeObjectURL(down.href) // 释放URL 对象
          // document.body.removeChild(down) //下载完成移除
        },
        (err) => {
          reject(err)
        }
      )
    })
  }
}

export default LZRequest
